import { timezones } from '@/typrs/timestamp';
import { useCallback, useEffect, useState } from 'react';

export const useTimestamp = () => {
    // 当前时间戳
    const [currentTimestamp, setCurrentTimestamp] = useState<number>(Math.floor(Date.now() / 1000));
    // 输入的时间戳
    const [timestamp, setTimestamp] = useState<string>('');
    // 转换后的日期时间
    const [dateTime, setDateTime] = useState<string>('');
    // 输入的日期时间
    const [inputDateTime, setInputDateTime] = useState<string>('');
    // 转换后的时间戳
    const [convertedTimestamp, setConvertedTimestamp] = useState<string>('');
    // 时间戳单位
    const [timestampUnit, setTimestampUnit] = useState<string>('milliseconds');
    // 选择的时区
    const [timezone, setTimezone] = useState<string>('Asia/Shanghai');
    // 复制成功提示
    const [copySuccess, setCopySuccess] = useState<string>('');
    // 错误信息
    const [error, setError] = useState<string>('');

    // 更新当前时间戳
    const updateCurrentTime = useCallback(() => {
        const now = new Date();
        setCurrentTimestamp(Math.floor(now.getTime() / 1000));
    }, []);

    // 组件挂载和每秒更新当前时间戳
    useEffect(() => {
        updateCurrentTime();
        const intervalId = setInterval(updateCurrentTime, 1000);
        return () => clearInterval(intervalId);
    }, [updateCurrentTime]);

    // 格式化日期时间，考虑时区
    const formatDateWithTimezone = useCallback((date: Date): string => {
        try {
            // 使用toLocaleString根据时区格式化日期
            return date.toLocaleString('zh-CN', {
                timeZone: timezone,
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-');
        } catch (error) {
            // 如果时区不支持，回退到ISO字符串
            console.error('时区格式化错误:', error);
            return date.toISOString().replace('T', ' ').substring(0, 19);
        }
    }, [timezone]);

    // 时间戳转日期时间
    const convertTimestampToDateTime = useCallback(() => {
        try {
            setError('');
            if (!timestamp.trim()) {
                setDateTime('');
                return;
            }

            const parsedTimestamp = parseInt(timestamp.trim(), 10);
            if (isNaN(parsedTimestamp)) {
                throw new Error('请输入有效的数字时间戳');
            }

            // 根据选择的单位转换为毫秒
            const timestampInMs = timestampUnit === 'seconds'
                ? parsedTimestamp * 1000
                : parsedTimestamp;

            const date = new Date(timestampInMs);

            // 检查日期是否有效
            if (isNaN(date.getTime())) {
                throw new Error('无效的时间戳');
            }

            // 格式化日期时间，考虑时区
            const formattedDateTime = formatDateWithTimezone(date);
            setDateTime(formattedDateTime);
        } catch (err) {
            setError(err instanceof Error ? err.message : '转换失败');
            setDateTime('');
        }
    }, [timestamp, timestampUnit, formatDateWithTimezone]);

    // 日期时间转时间戳
    const convertDateTimeToTimestamp = useCallback(() => {
        try {
            setError('');
            if (!inputDateTime.trim()) {
                setConvertedTimestamp('');
                return;
            }

            // 尝试解析日期时间
            const date = new Date(inputDateTime.trim());
            if (isNaN(date.getTime())) {
                throw new Error('请输入有效的日期时间');
            }

            // 根据选择的单位转换
            const timestampValue = timestampUnit === 'seconds'
                ? Math.floor(date.getTime() / 1000)
                : date.getTime();

            setConvertedTimestamp(timestampValue.toString());
        } catch (err) {
            setError(err instanceof Error ? err.message : '转换失败');
            setConvertedTimestamp('');
        }
    }, [inputDateTime, timestampUnit]);

    // 复制到剪贴板
    const copyToClipboard = useCallback((text: string) => {
        navigator.clipboard.writeText(text)
            .then(() => {
                setCopySuccess('已复制到剪贴板');
                setTimeout(() => setCopySuccess(''), 2000);
            })
            .catch(() => {
                setError('复制失败');
            });
    }, []);

    // 使用当前时间戳
    const useCurrentTimestamp = useCallback(() => {
        timestampUnit === 'seconds' ? setTimestamp(currentTimestamp.toString()) : setTimestamp((currentTimestamp * 1000).toString());
        setDateTime('');
    }, [currentTimestamp, convertTimestampToDateTime, timestampUnit]);

    // 使用当前日期时间
    const useCurrentDateTime = useCallback(() => {
        const now = new Date();
        const formattedDateTime = formatDateWithTimezone(now);
        setInputDateTime(formattedDateTime);
        setConvertedTimestamp('');
    }, [convertDateTimeToTimestamp, formatDateWithTimezone]);

    // 获取当前时区的当前时间
    const getCurrentTimeInTimezone = useCallback(() => {
        const now = new Date();
        return formatDateWithTimezone(now);
    }, [formatDateWithTimezone]);

    // 清除错误信息
    const clearError = useCallback(() => {
        setError('');
    }, []);

    // 清除复制成功提示
    const clearCopySuccess = useCallback(() => {
        setCopySuccess('');
    }, []);

    return {
        // 状态
        currentTimestamp,
        timestamp,
        dateTime,
        inputDateTime,
        convertedTimestamp,
        timestampUnit,
        timezone,
        copySuccess,
        error,
        // 设置函数
        setTimestamp,
        setInputDateTime,
        setTimestampUnit,
        setTimezone,
        // 操作函数
        convertTimestampToDateTime,
        convertDateTimeToTimestamp,
        copyToClipboard,
        useCurrentTimestamp,
        useCurrentDateTime,
        getCurrentTimeInTimezone,
        clearError,
        clearCopySuccess,
        // 时区列表
        timezones
    };
};